package com.moter.demo01.juc.reflect;

import java.lang.annotation.*;
import java.util.ArrayList;
import java.util.List;

@Table("student")
public class Student {
    @Field("st_name")
    private String name;
    @Field(value = "st_age",type = Type.INT)
    private Integer age;

    public static void main(String[] args) throws NoSuchFieldException {
        //根据注解反射来自动创建表a
        Class<Student> studentClass = Student.class;
        List<String> fields = new ArrayList<>();
        for (java.lang.reflect.Field declaredField : studentClass.getDeclaredFields()) {
            declaredField.setAccessible(true);
            Field annotation = declaredField.getAnnotation(Field.class);
            String field = annotation.value()+" "+annotation.type();
            fields.add(field);
        }
        String tableName = studentClass.getAnnotation(Table.class).value();
        System.out.println(sql(tableName,fields));

    }
    public static String sql(String tableName, List<String> fields){
        String sql = "create table "+tableName+" (";
        for (int i = 0; i < fields.size()-1; i++) {
            sql+=fields.get(i)+",";
        }
        sql+=fields.get(fields.size()-1)+")";
        return sql;
    }
}

@Target(ElementType.TYPE)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface Table {
    String value();
}

@Target(ElementType.FIELD)
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@interface Field {

    String value();//字段名
    Type type() default Type.VARCHAR;//字段类型，默认为varchar（20）
}
enum Type{
    VARCHAR(20),INT,TEXT;
    private Integer length;
    Type(int length){
        this.length=length;
    }
    Type(){}

}
